﻿
$(document).ready(function () {
    $("#ajax-page-tree").jstree({
        "json_data": {
            "ajax": {
                "async": true,
                "opts": {
                    "method": "POST",
                    "url": "/admin/page/getallnodes"
                },
                "type": "POST",
                "dataType": "json",
                "contentType": "application/json; charset=utf-8",
                "url": "/admin/page/getallnodes",
                "data": function (node) {
                    if (node == -1) {
                        return '{ "operation" : "get_children", "id" : -1 }';
                    } else {
                        return '{ "operation" : "get_children", "id" : ' + $(node).attr("id") + ', "type" : "' + $(node).attr("rel") + '", "date" : "' + $(node).attr("date") + '" }';
                    }
                },
                "success": function (retval) {
                    return retval.d;
                }
            }
        },
        "contextmenu": {
            'items': customMenu
        },
        "ui": {
            "select_limit": 1,
        },
        "types": {
            "valid_children": ["none"],
            "types": {
                "file": {
                    "valid_children": "none",
                    "icon": {
                        "image": "/content/images/glyphicons-halflings.png",
                        "position": "-24px -24px"
                    }
                },
                "folder": {
                    "valid_children": ["file", "folder"],
                    "icon": {
                        "image": "/content/images/glyphicons-halflings.png",
                        "position": "-384px -120px"
                    }
                },
                "drive": {
                    "valid_children": ["file", "folder"],
                    "icon": {
                        "image": "/content/images/glyphicons-halflings.png",
                        "position": "-384px -120px"
                    },
                    "start_drag": false,
                    "move_node": false,
                    "delete_node": false,
                    "remove": false
                }
            }
        },
        "plugins": ["themes", "json_data", "dnd", "ui", "crrm", "types", "contextmenu"]
    }).bind("rename.jstree", function (e, data) {

        var node = {
            id: data.rslt.obj.attr("id"),
            type: data.rslt.obj.attr("rel"),
            newTitle: data.rslt.new_name
        };

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "/admin/page/rename",
            data: JSON.stringify(node)
        });

    }).bind("remove.jstree", function (e, data) {

        var node = {
            id: data.rslt.obj.attr("id"),
            type: data.rslt.obj.attr("rel")
        };

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "/admin/page/remove",
            data: JSON.stringify(node)
        });

    }).bind("create.jstree", function (e, data) {

        var nameReg = /^[0-9A-Za-z\s]+$/;
        if (!nameReg.test(data.rslt.name)) {
            $.jstree.rollback(data.rlbk);
            return;
        }

        var node = {
            parentId: data.rslt.parent.attr("id"),
            title: data.rslt.name,
            type: data.rslt.obj.attr("rel")
        };

        var type = node.type;

        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "/admin/page/addnode",
            data: JSON.stringify(node),
            success: function (msg) {
                data.rslt.obj.attr("id", msg).attr("rel", type);
            }
        });

    }).bind("move_node.jstree", function (e, data) {

        data.rslt.o.each(function (i) {
            var node = {
                id: $(this).attr("id"),
                parentId: data.rslt.np.attr("id"),
                type: $(this).attr("rel")
            };

            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                url: "/admin/page/movenode",
                data: JSON.stringify(node)
            });
        });
    }).bind('loaded.jstree', function (e, data) {

        var depth = 1;
        data.inst.get_container().find('li').each(function (i) {
            if (data.inst.get_path($(this)).length <= depth) {
                data.inst.open_node($(this));
            }
        });

    });

    $(document).on("click", "li[rel='file'] > a, li[rel='folder'] > a, li[rel='drive'] > a", function () {
        $("#ajax-page-tree div.button-edit, div.button-delete").each(function () { $(this).remove(); });

        if ($(this).parent().attr('rel') == 'drive')
            return;

        if ($(this).parent().attr('rel') == 'folder')
            $(this).after("<div id='" + $(this).parent().attr("id") + "' rel='" + $(this).parent().attr("rel") + "' class='button-delete'></div>");
        else
            $(this).after("<div id='" + $(this).parent().attr("id") + "' rel='" + $(this).parent().attr("rel") + "' class='button-edit'></div><div id='" + $(this).parent().attr("id") + "' rel='" + $(this).parent().attr("rel") + "' class='button-delete'></div>");
    });

    $(document).on("click", ".button-edit", function () {
        if ($(this).attr("rel") == "file") {
            var pid = $(this).attr("id");

            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                url: "/admin/page/editpage",
                data: JSON.stringify({ id: pid }),
                success: function (msg) { databind(msg); }
            });

        } else
            if ($(this).attr("rel") == "folder") {
                alert("need form!");
            }
    });

    function databind(msg) {
        $("#editEntryForm").attr('action', "/admin/page/edit/" + msg.Id);

        //hiddens
        $("#Page_Id").val(msg.Id);
        $("#Page_CreatedAt").val(msg.CreatedAt);
        $("#Page_Alias").val(msg.Alias);
        $("#Page_ModifiedAt").val(msg.ModifiedAt);
        $("#Page_StatusId").val(msg.PageStatusId);
        $("#Page_AuthorId").val(msg.AuthorId);

        CKEDITOR.instances["pageContent"].setData(msg.PageContent);

        $("#Page_PageTitle").val(msg.PageTitle);
        $("#Page_CategoryId").val(msg.CategoryId);

        $("#permalinkUrl").attr('href', '/pages/' + msg.Alias);
        $("#pageUrl").text("http://" + window.location.host + "/pages/");
        $("#pagePermalink").text(msg.Alias);
        $("#txtNewPageAlias").val(msg.Alias);
        $('#permalink').show();

        $('#tags').importTags(msg.Tags);

        $("#Page_SeoTitle").val(msg.SeoTitle);
        $("#Page_MetaKeywords").val(msg.MetaKeywords);
        $("#Page_MetaDescription").val(msg.MetaDescription);

        $("#PageStatusId").val(msg.PageStatusId);

        $("#Page_ShowRating").attr("checked", msg.ShowRating);
        $("#Page_ShowRating").attr("value", msg.ShowRating);
        $('input:hidden[name="Page.ShowRating"]').val(msg.ShowRating);

        $("#Page_HasComments").attr("checked", msg.HasComments);
        $("#Page_HasComments").attr("value", msg.HasComments);
        $('input:hidden[name="Page.HasComments"]').val(msg.HasComments);
    }

    $(":checkbox").change(function () {
        $("input:hidden[name='" + ($(this)).attr("name") + "']").val((this).checked);
    });

    $(document).on("click", ".button-delete", function () {
        var self = $(this);
        bootbox.dialog({
            message: "Are you sure want to delete this item?",
            title: "Delete",
            buttons: {
                success: {
                    label: "Ok",
                    className: "btn-success",
                    callback: function () {

                        var node = {
                            id: self.parent().attr("id"),
                            type: self.parent().attr("rel")
                        };

                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            url: "/admin/page/remove",
                            data: JSON.stringify(node),
                            success: function (msg) {
                                if (msg.success == true)
                                    $("li#" + node.id + "[rel='" + node.type + "']").hide(300);
                            }
                        });
                    }
                },
                danger: {
                    label: "Cancel",
                    className: "btn-danger",
                }
            }
        });
    });
});

function refresh() {
    $("#ajax-page-tree").jstree("refresh");
}

function customMenu(node) {
    var items = {
        Edit: {
            label: "Edit",
            action: function (obj) {
                if (obj.attr("rel") == "file") {
                    window.location.href = '/page/edit/' + obj.attr("id");
                } else if (obj.attr("rel") == "folder") {
                    return;
                }
            }
        },
        Create_file: {
            label: "Create page",
            action: function (obj) {
                this.create(obj);
            }
        },
        Create_folder: {
            label: "Create folder",
            action: function (obj) {
                this.create(obj, "last", { "attr": { "rel": "folder" } });
            }
        },
        Rename: {
            label: "Rename",
            action: function (obj) {
                this.rename(obj);
            }
        },
        Delete: {
            label: "Delete",
            action: function (obj) {
                var self = this;
                bootbox.dialog({
                    message: "Are you sure want to delete this item?",
                    title: "Delete",
                    buttons: {
                        success: {
                            label: "Ok",
                            className: "btn-success",
                            callback: function () {
                                self.remove(obj);
                            }
                        },
                        danger: {
                            label: "Cancel",
                            className: "btn-danger",
                        }
                    }
                });
            }
        }
    };

    if ($(node).attr("rel") == "drive") {
        delete items.Delete;
        delete items.Edit;
        delete items.Rename;
    } else if ($(node).attr("rel") == "folder") {
        delete items.Edit;
    } else if ($(node).attr("rel") == "file") {
        delete items.Create_folder;
        delete items.Create_file;
    }

    return items;
}
